package com.ruoyi.cm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.base.domain.BaseBsZd;
import com.ruoyi.base.mapper.BaseBsZdMapper;
import com.ruoyi.cm.domain.CmBsQs;
import com.ruoyi.cm.domain.CmReport;
import com.ruoyi.cm.domain.bo.CmBdQsCountBo;
import com.ruoyi.cm.domain.bo.CmReportBo;
import com.ruoyi.cm.domain.vo.CmBaContractSheetsVo;
import com.ruoyi.cm.domain.vo.CmBsQsVo;
import com.ruoyi.cm.mapper.CmBaContractSheetsMapper;
import com.ruoyi.cm.mapper.CmBsQsMapper;
import com.ruoyi.cm.mapper.CmReportMapper;
import com.ruoyi.cm.service.ICmBdQsCountService;
import com.ruoyi.cm.service.ICmReportService;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.data.querydsl.QSort;
import org.springframework.stereotype.Service;
import com.ruoyi.cm.domain.bo.CmPeriodMeasurementBo;
import com.ruoyi.cm.domain.vo.CmPeriodMeasurementVo;
import com.ruoyi.cm.domain.CmPeriodMeasurement;
import com.ruoyi.cm.mapper.CmPeriodMeasurementMapper;
import com.ruoyi.cm.service.ICmPeriodMeasurementService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 中间计量Service业务层处理
 *
 * @author zxs
 * @date 2024-09-28
 */
@RequiredArgsConstructor
@Service
public class CmPeriodMeasurementServiceImpl implements ICmPeriodMeasurementService {

    private final CmPeriodMeasurementMapper baseMapper;

    private final CmBaContractSheetsMapper contractSheetsMapper;
    private final CmBsQsMapper qsMapper;
    private final BaseBsZdMapper zdMapper;
    private final ICmReportService reportService;
    private final CmReportMapper reportMapper;


    private final ICmBdQsCountService bdQsCountService;

    /**
     * 查询中间计量
     */
    @Override
    public CmPeriodMeasurementVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询中间计量列表
     */
    @Override
    public TableDataInfo<CmPeriodMeasurementVo> queryPageList(CmPeriodMeasurementBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CmPeriodMeasurement> lqw = buildQueryWrapper(bo);
        Page<CmPeriodMeasurementVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询中间计量列表
     */
    @Override
    public List<CmPeriodMeasurementVo> queryList(CmPeriodMeasurementBo bo) {
        LambdaQueryWrapper<CmPeriodMeasurement> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CmPeriodMeasurement> buildQueryWrapper(CmPeriodMeasurementBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CmPeriodMeasurement> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getQsId() != null, CmPeriodMeasurement::getQsId, bo.getQsId());
        lqw.eq(bo.getMeasurementQuantity() != null, CmPeriodMeasurement::getMeasurementQuantity, bo.getMeasurementQuantity());
        lqw.eq(bo.getTotalPrice() != null, CmPeriodMeasurement::getTotalPrice, bo.getTotalPrice());
        lqw.eq(bo.getRemainingQuantity() != null, CmPeriodMeasurement::getRemainingQuantity, bo.getRemainingQuantity());
        lqw.eq(bo.getBdId() != null, CmPeriodMeasurement::getBdId, bo.getBdId());
        lqw.eq(StringUtils.isNotBlank(bo.getFileNo()), CmPeriodMeasurement::getFileNo, bo.getFileNo());
        lqw.eq(bo.getContractListId() != null, CmPeriodMeasurement::getContractListId, bo.getContractListId());
        lqw.eq(bo.getQs() != null, CmPeriodMeasurement::getQs, bo.getQs());
        lqw.eq(bo.getChgRongliang() != null, CmPeriodMeasurement::getChgRongliang, bo.getChgRongliang());
        lqw.eq(bo.getChgZongjia() != null, CmPeriodMeasurement::getChgZongjia, bo.getChgZongjia());
        return lqw;
    }

    /**
     * 新增中间计量
     */
    @Override
    public Boolean insertByBo(CmPeriodMeasurementBo bo) {
        CmPeriodMeasurement add = BeanUtil.toBean(bo, CmPeriodMeasurement.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 1、报表审批完成情况下，中间计量数据不能改动；持久化原则；
     * 2、未审批的情况下，除计量数量，合价，未计量数量外，全部以合同清单为准；
     * 批量修改中间计量，同一站点下的同一合同清单id的中间计量数据共用最新的剩余数量（所有期数）；
     * 2、计算本期计量金额(每站点当期计量金额合价)、累计计量金额(已计量期数的本期计量金额合计)、本期支付金额(本期计量金额-扣回开工预付金额+奖罚金)、
     * 累计支付金额(开工预付款-奖励基金+已计量期数的本期支付金额合计)并保存。
     */
    @Override
    @DSTransactional
    public Boolean updateByBo(CmPeriodMeasurementBo bo) {
        List<CmPeriodMeasurement> measurementBos = bo.getMeasurementBos();
        if(CollUtil.isEmpty(measurementBos)){
            return true;
        }
        //查询当前标段、站点下所有中间计量数据；
        LambdaQueryWrapper<CmPeriodMeasurement> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CmPeriodMeasurement::getBdId,bo.getBdId());
        lqw.eq(CmPeriodMeasurement::getZdId,bo.getZdId());
        //根据标段和站点id查询所有期次的中间计量列表；
        List<CmPeriodMeasurement> measurements = baseMapper.selectList(lqw);
        //根据标段id查询各期次下的报表审批状态，审批中或已审批的中间计量数据不能修改；
        List<CmReport> cmReports = reportMapper.selectList(new LambdaQueryWrapper<CmReport>().eq(CmReport::getBdId,bo.getBdId()));
        Map<Long, String> reportStatusMap = cmReports.stream().filter(e->e.getZdId() == null).collect(Collectors.toMap(CmReport::getQsId, CmReport::getStatus));
        measurements.forEach(e-> {
            BigDecimal remainingQuantity;
//            审批状态为未审批00或已驳回33的才进行修改；
            if(CollUtil.isEmpty(reportStatusMap)||("00".equals(reportStatusMap.get(e.getQsId()))||"33".equals(reportStatusMap.get(e.getQsId())))){
                for (CmPeriodMeasurement o : measurementBos) {
                    remainingQuantity = o.getRemainingQuantity();
                    //将前端传的数据复制到要更新的对象里；
                    if (e.getContractListId().equals(o.getContractListId()) && e.getQsId().equals(o.getQsId())) {
                        BeanUtil.copyProperties(o, e);
                    }
                    //将前端传的不为空的剩余数量复制到相同合同清单id下不同期数的对象里；
                    if (e.getContractListId().equals(o.getContractListId()) && remainingQuantity != null) {
                        e.setRemainingQuantity(remainingQuantity);
                    }
                }
            }
        });
        boolean b = baseMapper.updateBatchById(measurements);
        //更新标段站点期数计量表；
        CmBdQsCountBo qsCountBo = new CmBdQsCountBo();
        qsCountBo.setBdId(bo.getBdId());
        qsCountBo.setZdId(bo.getZdId());
        qsCountBo.setQsId(bo.getQsId());
        bdQsCountService.update(qsCountBo);
        return b;
    }


    /**   查询中间计量表
     * 1、报表审批完成情况下，中间计量数据不能改动；持久化原则；
     * 2、未审批的情况下，除计量数量，合价，未计量数量外，全部以合同清单为准；
     * @param bo
     *
     * @return
     */
    @Override
    public List<CmPeriodMeasurementVo> getlist(CmPeriodMeasurementBo bo) {
        Long bdId = bo.getBdId();
        Long zdId = bo.getZdId();
        Long qsId = bo.getQsId();
        if(bdId == null || zdId == null || qsId == null){
            return new ArrayList<>();
        }
        // 查询对应的合同站点清单
        List<CmBaContractSheetsVo> sheetsVos = contractSheetsMapper.selectContractDataList(String.valueOf(bdId),String.valueOf(zdId));
        List<CmPeriodMeasurementVo> viewList = new ArrayList<>();

        // 查询中间计量表
        if (CollUtil.isNotEmpty(sheetsVos)) {


            // 合同站点清单id集合
            Set<Long> sheetIds = sheetsVos.stream().map(CmBaContractSheetsVo::getSheetId).collect(Collectors.toSet());

            CmBsQsVo cmBsQsVo = qsMapper.selectVoById(qsId);
            // 查询该站点下是否有数据,没有则添加全部期数数据,有则只添加当前期数数据
            LambdaQueryWrapper<CmPeriodMeasurement> lqw3 = new LambdaQueryWrapper<>();
            lqw3.in(CmPeriodMeasurement::getContractListId, sheetIds);
            lqw3.eq(CmPeriodMeasurement::getZdId,bo.getZdId());
//            lqw3.eq(CmPeriodMeasurement::getQsId,qsId);
            List<CmPeriodMeasurement> allPeriodList = baseMapper.selectList(lqw3);
            List<CmPeriodMeasurement> data = allPeriodList.stream().filter(e->qsId.equals(e.getQsId())).collect(Collectors.toList());

            List<CmPeriodMeasurement> insertList = new ArrayList<>();
            Set<Long> contractListids = data.stream().map(CmPeriodMeasurement::getContractListId).collect(Collectors.toSet());
            if (CollUtil.isEmpty(data)||sheetsVos.size() > data.size()) {
                // 遍历添加所有清单信息
                sheetsVos.forEach(item -> {
                    // 遍历添加当前清单所有期数信息
                    if (CollUtil.isEmpty(data) || (!contractListids.contains(item.getSheetId()))) {
                        CmPeriodMeasurement entity = new CmPeriodMeasurement();
                        entity.setBdId(bdId);
                        entity.setZdId(zdId);
                        entity.setQsId(qsId);
                        entity.setContractListId(item.getSheetId());
                        entity.setQs(cmBsQsVo.getSettleIndex());
                        entity.setInitRongliang(item.getInitRongliang());
                        entity.setChgRongliang(item.getChgRongliang());
//                        entity.setTotalPrice(item.getInitZongjia());
                        entity.setChgZongjia(item.getChgZongjia());
                        // 合同站点清单变更审批通过状态下
                        // 默认值: 数量+变更数量-计量数量 = 剩余数量(未计量数量)
                        if (ObjectUtils.isNotEmpty(item.getChgApprovalStatus()) && "22".equals(item.getApprovalStatus()) &&
                            ObjectUtils.isNotEmpty(item.getInitRongliang()) && ObjectUtils.isNotEmpty(item.getChgRongliang())) {
                            entity.setRemainingQuantity(item.getInitRongliang().add(item.getChgRongliang()).subtract(BigDecimal.ZERO));
                        } else {
                            entity.setRemainingQuantity(item.getInitRongliang());
                        }
                        entity.setChgRongliang(item.getChgRongliang());
                        entity.setChgZongjia(item.getChgZongjia());
                        insertList.add(entity);
                    }
                });
                baseMapper.insertOrUpdateBatch(insertList);
                List<CmPeriodMeasurement> addList = insertList.stream().filter(e -> e.getQsId().equals(qsId)).collect(Collectors.toList());
                data.addAll(addList);
            }
            // 筛选当前期数据
            viewList = BeanUtil.copyToList(data, CmPeriodMeasurementVo.class);
            // 赋值
            //查询报表管理各期次的审批状态，状态为已审批“22”和审批中“11”的不处理，
            //查询报表管理审批状态；
            CmReportBo reportBo = new CmReportBo();
            reportBo.setQsId(qsId);
            reportBo.setBdId(bdId);
            CmReport info = reportService.getInfo(reportBo);
            //00 未审批，11 审批中， 22 已审批， 33 已驳回；
            String status = info.getStatus();

                viewList.forEach(item -> {
                    item.setInitZongjia(item.getTotalPrice());
                    CmBaContractSheetsVo vo = sheetsVos.stream().filter(e -> e.getSheetId().equals(item.getContractListId())).findFirst().get();
                        if("00".equals(status)||"33".equals(status)) {
                            BeanUtil.copyProperties(vo, item);
                        }else{
                            item.setSheetTypeName(vo.getSheetTypeName());
                            item.setSheetFeaturesName(vo.getSheetFeaturesName());
                            item.setSheetUnit(vo.getSheetUnit());
                            item.setInitDanjia(vo.getInitDanjia());
                            item.setSheetTaxRate(vo.getSheetTaxRate());
                        }
                });
//            按照编号排序
            Collections.sort(viewList, (t1,t2)-> {
                if (StringUtils.isBlank(t1.getSheetTypeCode()) && StringUtils.isBlank(t2.getSheetTypeCode())) {
                    return 0;
                }
                if (StringUtils.isBlank(t1.getSheetTypeCode())) {
                    return -1;
                }
                if (StringUtils.isBlank(t2.getSheetTypeCode())) {
                    return 1;
                }
                return t1.getSheetTypeCode().compareTo(t2.getSheetTypeCode());
            });
        }
        return viewList;
    }

    /**
     * 返回标段下所有站点中间计量信息列表；站点名称，实际合同额，计量金额；
     * @param bo
     * @return
     */
    @Override
    public List<CmPeriodMeasurementVo> getbdlist(CmPeriodMeasurementBo bo) {
        List<CmPeriodMeasurementVo> returnList = new ArrayList<>();
        Long bdId = bo.getBdId();
        if (bdId == null) {
            return returnList;
        }
        List<BaseBsZd> zdList = zdMapper.selectList(new LambdaQueryWrapper<BaseBsZd>().eq(BaseBsZd::getBdId, bdId));
        List<CmBsQs> qsList = qsMapper.selectList(new LambdaQueryWrapper<CmBsQs>().eq(CmBsQs::getBdId, bdId).orderByAsc(CmBsQs::getSettleIndex));
        Set<Long> qsIds = qsList.stream().map(CmBsQs::getQsId).collect(Collectors.toSet());
        if (CollUtil.isEmpty(qsIds)) {
            return returnList;
        }
        List<CmPeriodMeasurement> measurements = baseMapper.selectList(new LambdaQueryWrapper<CmPeriodMeasurement>().eq(CmPeriodMeasurement::getBdId, bdId));
        Map<Long, List<CmPeriodMeasurement>> zdMaps = measurements.stream().filter(e -> qsIds.contains(e.getQsId())).collect(Collectors.groupingBy(CmPeriodMeasurement::getZdId));
        if (CollUtil.isNotEmpty(zdList)) {
            for (BaseBsZd zd : zdList) {
                List<CmPeriodMeasurement> measurementList = zdMaps.get(zd.getId());
                BigDecimal jlje = new BigDecimal("0.00");
                if (CollUtil.isNotEmpty(measurementList)) {
                    Map<Long, List<CmPeriodMeasurement>> qsMeasurements = measurementList.stream().collect(Collectors.groupingBy(CmPeriodMeasurement::getQsId));
                    for (CmBsQs qs : qsList) {
                        BigDecimal bqjlje = new BigDecimal("0.00");
                        List<CmPeriodMeasurement> measurements1 = qsMeasurements.get(qs.getQsId());
                        CmPeriodMeasurementVo vo = new CmPeriodMeasurementVo();
                        vo.setZdName(zd.getName());
                        vo.setSjhte(zd.getZdContractAmountActual());
                        vo.setQs(qs.getSettleIndex());
                        vo.setJlje(jlje);
                        vo.setBqjlje(bqjlje);
                        returnList.add(vo);
                        if (CollUtil.isNotEmpty(measurements1)) {
                            for (CmPeriodMeasurement ment : measurements1) {
                                jlje = BigDecimalUtil.add(jlje, ment.getTotalPrice() == null ? new BigDecimal("0.00") : ment.getTotalPrice());
                                bqjlje = BigDecimalUtil.add(bqjlje, ment.getTotalPrice() == null ? new BigDecimal("0.00") : ment.getTotalPrice());
                            }
                            if (bqjlje.compareTo(BigDecimal.ZERO) > 0) {
                                vo.setBqjlje(bqjlje);
                            }
                        }
                    }
                    BigDecimal finalJlje = jlje;
                    returnList.stream().filter(e->zd.getName().equals(e.getZdName())).forEach(e->e.setJlje(finalJlje));
                }
            }
        }
        if(CollUtil.isNotEmpty(returnList)){
            returnList = returnList.stream().filter(e -> e.getJlje().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
        }
        return returnList;
    }


    /**
     * 批量删除中间计量
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CmPeriodMeasurement entity){
        //TODO 做一些数据校验,如唯一约束
    }


    // 查询中间计量表
    public List<CmPeriodMeasurementVo> getlist1(CmPeriodMeasurementBo bo) {
        Long bdId = bo.getBdId();
        Long zdId = bo.getZdId();
        Long qsId = bo.getQsId();

        // 查询对应的合同站点清单
        List<CmBaContractSheetsVo> sheetsVos = contractSheetsMapper.selectContractDataList(String.valueOf(bdId),String.valueOf(zdId));
        List<CmPeriodMeasurementVo> viewList = new ArrayList<>();

        // 查询中间计量表
        if (CollUtil.isNotEmpty(sheetsVos)) {
            // 合同站点清单id集合
            Set<Long> sheetIds = sheetsVos.stream().map(CmBaContractSheetsVo::getSheetId).collect(Collectors.toSet());

            LambdaQueryWrapper<CmPeriodMeasurement> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(qsId != null, CmPeriodMeasurement::getQsId, qsId);
            wrapper.eq(zdId != null, CmPeriodMeasurement::getZdId, zdId);
            wrapper.in(CollUtil.isNotEmpty(sheetIds), CmPeriodMeasurement::getContractListId, sheetIds);
            List<CmPeriodMeasurement> list = baseMapper.selectList(wrapper);

            // 获取当前期数信息
            LambdaQueryWrapper<CmBsQs> lqw = new LambdaQueryWrapper<>();
            lqw.eq(bdId != null, CmBsQs::getBdId, bdId);
            lqw.eq(qsId != null, CmBsQs::getQsId, qsId);
            CmBsQs currQs = qsMapper.selectOne(lqw);

            // 获取该站点全部期数信息
            LambdaQueryWrapper<CmBsQs> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(bdId != null, CmBsQs::getBdId, bdId);
            List<CmBsQs> allQs = qsMapper.selectList(lqw2);

            // 如果不存在则新增
            if (CollUtil.isEmpty(list)) {
                // 查询该站点下是否有数据,没有则添加全部期数数据,有则只添加当前期数数据
                LambdaQueryWrapper<CmPeriodMeasurement> lqw3 = new LambdaQueryWrapper<>();
                lqw3.in(CmPeriodMeasurement::getContractListId, sheetIds);
                lqw3.eq(CmPeriodMeasurement::getZdId,bo.getZdId());
                List<CmPeriodMeasurement> data = baseMapper.selectList(lqw3);

                List<CmPeriodMeasurement> insertList = new ArrayList<>();
                if (CollUtil.isEmpty(data)) {
                    // 遍历添加所有清单信息
                    sheetsVos.forEach(item -> {
                        // 遍历添加当前清单所有期数信息
                        allQs.forEach(curr -> {
                            CmPeriodMeasurement entity = new CmPeriodMeasurement();
                            entity.setBdId(bdId);
                            entity.setZdId(zdId);
                            entity.setQsId(curr.getQsId());
                            entity.setContractListId(item.getSheetId());
                            entity.setQs(curr.getSettleIndex());
                            // 合同站点清单变更审批通过状态下
                            // 默认值: 数量+变更数量-计量数量 = 剩余数量(未计量数量)
                            if (ObjectUtils.isNotEmpty(item.getChgApprovalStatus()) && "22".equals(item.getApprovalStatus()) &&
                                ObjectUtils.isNotEmpty(item.getInitRongliang()) && ObjectUtils.isNotEmpty(item.getChgRongliang())) {
                                entity.setRemainingQuantity(item.getInitRongliang().add(item.getChgRongliang()).subtract(BigDecimal.ZERO));
                            } else {
                                entity.setRemainingQuantity(item.getInitRongliang());
                            }
                            entity.setChgRongliang(item.getChgRongliang());
                            entity.setChgZongjia(item.getChgZongjia());
                            insertList.add(entity);
                        });

                    });
                    list = insertList.stream().filter(e -> e.getQsId().equals(qsId)).collect(Collectors.toList());
                } else {
                    // 遍历添加对应期数所有清单信息
                    sheetsVos.forEach(item -> {
                        // 查询历史第一期的剩余数量(未计量数量)
                        LambdaQueryWrapper<CmPeriodMeasurement> lqw4 = new LambdaQueryWrapper<>();
                        lqw4.eq(CmPeriodMeasurement::getQs, 1);
                        lqw4.eq(item.getSheetId() != null, CmPeriodMeasurement::getContractListId, item.getSheetId());
                        lqw4.eq(zdId != null, CmPeriodMeasurement::getZdId, zdId);
                        CmPeriodMeasurement one = baseMapper.selectOne(lqw4);

                        CmPeriodMeasurement entity = new CmPeriodMeasurement();
                        entity.setBdId(bdId);
                        entity.setZdId(zdId);
                        entity.setQsId(currQs.getQsId());
                        entity.setContractListId(item.getSheetId());
                        entity.setQs(currQs.getSettleIndex());
                        // 剩余数量赋值
                        if (ObjectUtils.isNotEmpty(one)) {
                            entity.setRemainingQuantity(one.getRemainingQuantity());
                            // 变更状态是22通过时,则赋值清单中查询出来的变更值,否则赋值第一期变更值
                            if ("22".equals(item.getChgApprovalStatus())) {
                                entity.setChgRongliang(item.getChgRongliang());
                                entity.setChgZongjia(item.getChgZongjia());
                            } else {
                                entity.setChgRongliang(one.getChgRongliang());
                                entity.setChgZongjia(one.getChgZongjia());
                            }
                        }
                        insertList.add(entity);
                    });
                    list = insertList;
                }
                baseMapper.insertOrUpdateBatch(insertList);
            }
            // 筛选当前期数据
            viewList = BeanUtil.copyToList(list, CmPeriodMeasurementVo.class);
            // 赋值
            viewList.forEach(item -> {
                CmBaContractSheetsVo vo = sheetsVos.stream().filter(e -> e.getSheetId().equals(item.getContractListId())).findFirst().get();
                vo.setChgRongliang(item.getChgRongliang());
                vo.setChgZongjia(item.getChgZongjia());
                BeanUtil.copyProperties(vo, item);
            });
//            按照编号排序
            Collections.sort(viewList, (t1,t2)-> {
                if (StringUtils.isBlank(t1.getSheetTypeCode()) && StringUtils.isBlank(t2.getSheetTypeCode())) {
                    return 0;
                }
                if (StringUtils.isBlank(t1.getSheetTypeCode())) {
                    return -1;
                }
                if (StringUtils.isBlank(t2.getSheetTypeCode())) {
                    return 1;
                }
                return t1.getSheetTypeCode().compareTo(t2.getSheetTypeCode());
            });
        }
        return viewList;
    }

    //查询中间计量列表；
//    @Override
    @DSTransactional
    public List<CmPeriodMeasurementVo> getlist2(CmPeriodMeasurementBo bo) {
        Long bdId = bo.getBdId();
        Long zdId = bo.getZdId();
        Long qsId = bo.getQsId();
        List<CmBaContractSheetsVo> sheetsVos = contractSheetsMapper.selectContractDataList(String.valueOf(bdId),String.valueOf(zdId));

        List<CmPeriodMeasurementVo> result = new ArrayList<>();
        if (CollUtil.isNotEmpty(sheetsVos)) {
            //根据期数、合同清单id和站点id查询中间计量列表；
            Set<Long> sheetIds = sheetsVos.stream().map(CmBaContractSheetsVo::getSheetId).collect(Collectors.toSet());
            LambdaQueryWrapper<CmPeriodMeasurement> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CmPeriodMeasurement::getQsId, qsId);
            wrapper.in(CmPeriodMeasurement::getContractListId, sheetIds);
            wrapper.eq(CmPeriodMeasurement::getZdId,bo.getZdId());
            List<CmPeriodMeasurement> cmPeriodMeasurements = baseMapper.selectList(wrapper);

            // 中间计量按照清单分组
            Map<Long, CmPeriodMeasurement> measurementMap = cmPeriodMeasurements.stream().collect(Collectors.toMap(CmPeriodMeasurement::getContractListId, e -> e,(e1,e2)->e1));
            for (CmBaContractSheetsVo e : sheetsVos) {
                // 变更信息赋默认值
                if (ObjectUtils.isEmpty(e.getChgZongjia())) {
                    e.setChgZongjia(e.getInitZongjia());
                }
                CmPeriodMeasurementVo vo = new CmPeriodMeasurementVo();
                BeanUtil.copyProperties(e, vo);
                CmPeriodMeasurement measurement = measurementMap.get(e.getSheetId());
                vo.setQsId(qsId);
                vo.setContractListId(e.getSheetId());
                // 对应期数存在
                if (CollUtil.isNotEmpty(measurementMap) && measurement != null) {
                    vo.setMeasurementQuantity(measurement.getMeasurementQuantity());
                    vo.setTotalPrice(measurement.getTotalPrice());
                    if (measurement.getRemainingQuantity() != null) {
                        vo.setRemainingQuantity(measurement.getRemainingQuantity());
                    }
                    vo.setId(measurement.getId());
                } else {
                    // 对应期数不存在
                    // 先查询历史期数的剩余数量
                    BigDecimal remain = null;
                    Long preQsId = getPreQsId(bo.getBdId(), qsId);
                    if (preQsId != null) {
                        remain = getRemain(preQsId, e.getSheetId(), zdId);
                    }
                    // 标段-站点-清单-添加所有期数中间计量
                    LambdaQueryWrapper<CmBsQs> lqw = new LambdaQueryWrapper<>();
                    lqw.eq(bdId != null, CmBsQs::getBdId, bdId);
                    List<CmBsQs> cmBsQs = qsMapper.selectList(lqw);
                    Set<Long> qsIds = cmBsQs.stream().map(CmBsQs::getQsId).collect(Collectors.toSet());
                    BigDecimal finalRemain = remain;

                    qsIds.forEach(qs -> {
                        CmPeriodMeasurement periodMeasurement = new CmPeriodMeasurement();
                        periodMeasurement.setQsId(qs);
                        periodMeasurement.setContractListId(e.getSheetId());
                        periodMeasurement.setBdId(bdId);
                        periodMeasurement.setZdId(zdId);
                        if (finalRemain != null) {
                            periodMeasurement.setRemainingQuantity(finalRemain);
                        } else {
                            // 默认值: 数量+变更数量-计量数量 = 剩余数量(未计量数量)
                            if (ObjectUtils.isNotEmpty(e.getInitRongliang()) && ObjectUtils.isNotEmpty(e.getChgRongliang())) {
                                periodMeasurement.setRemainingQuantity(e.getInitRongliang().add(e.getChgRongliang()).subtract(BigDecimal.ZERO));
                            } else {
                                periodMeasurement.setRemainingQuantity(e.getInitRongliang());
                            }
                        }
                        baseMapper.insert(periodMeasurement);
                        vo.setRemainingQuantity(periodMeasurement.getRemainingQuantity());
                        vo.setId(periodMeasurement.getId());
                    });


//                    //查询标段下所有期数；当前标段、当前站点下 每条合同清单每个期次下都新增一条中间计量数据；
//                    LambdaQueryWrapper<CmBsQs> lqw = new LambdaQueryWrapper<>();
//                    lqw.eq(CmBsQs::getBdId, bo.getBdId());
//                    List<CmBsQs> cmBsQs = qsMapper.selectList(lqw);
//                    Set<Long> qsIds = cmBsQs.stream().map(CmBsQs::getQsId).collect(Collectors.toSet());
//                    qsIds.forEach(qs -> {
//                        CmPeriodMeasurement periodMeasurement = new CmPeriodMeasurement();
//                        periodMeasurement.setQsId(qs);
//                        periodMeasurement.setRemainingQuantity(e.getInitRongliang());
//                        periodMeasurement.setContractListId(e.getSheetId());
//                        periodMeasurement.setBdId(bo.getBdId());
//                        periodMeasurement.setZdId(bo.getZdId());
//                        baseMapper.insert(periodMeasurement);
//                        //将新增的id返回给前端；
//                        if (qs.equals(bo.getQsId())) {
//                            vo.setRemainingQuantity(e.getInitRongliang());
//                            vo.setId(periodMeasurement.getId());
//                        }
//                    });
                }
                result.add(vo);
            }
        }
        return result;
    }

    // 获取上一期期数id
    public Long getPreQsId(Long bdId, Long qsId) {
        LambdaQueryWrapper<CmBsQs> lqw = new LambdaQueryWrapper<>();
        lqw.eq(bdId != null, CmBsQs::getBdId, bdId);
        lqw.eq(qsId != null, CmBsQs::getQsId, qsId);
        CmBsQs cmBsQs = qsMapper.selectOne(lqw);
        Integer qs = cmBsQs.getSettleIndex();
        if (qs != null && qs != 1) {
            LambdaQueryWrapper<CmBsQs> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(bdId != null, CmBsQs::getBdId, bdId);
            lqw2.eq(qs != null, CmBsQs::getSettleIndex, qs-1);
            CmBsQs one = qsMapper.selectOne(lqw);
            return one.getQsId();
        } else {
            return null;
        }
    }

    // 查询历史期数的剩余数量
    public BigDecimal getRemain(Long qsId, Long contractListId, Long zdId) {
        LambdaQueryWrapper<CmPeriodMeasurement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(qsId != null, CmPeriodMeasurement::getQsId, qsId);
        wrapper.in(contractListId != null, CmPeriodMeasurement::getContractListId, contractListId);
        wrapper.eq(zdId != null, CmPeriodMeasurement::getZdId, zdId);
        List<CmPeriodMeasurement> data = baseMapper.selectList(wrapper);
        if (CollUtil.isNotEmpty(data)) {
            return data.get(0).getRemainingQuantity();
        } else {
            return null;
        }
    }

}
